가상 요소(Pseudo Element)

✒️ 2025-05-16 12:42 내용 수정


참고 자료 : mdn web docs CSS Pseudo elements, TCPSchool CSS 가상 요소

html에는 존재하지 않지만 CSS에서 만들어주는 inline 요소

selector::pseudo-element{
	/*적용할 스타일*/
}

/* 가상 클래스에 가상 요소 사용 시 */
selector:pseudo-class::pseudo-element{
	/*적용할 스타일*/
}
가상 요소 설명
::after 선택한 요소의 맨 마지막 자식으로 가상 요소 생성. 기본값 inline
::before 선택한 요소의 첫 번째 자식으로 가상 요소 생성. 기본값 inline
::first-letter 블록 컨테이너의 첫 번째 줄의 첫 번째 글자에 스타일을 적용하는 가상 요소 생성
::first-line 블록 컨테이너의 첫번째 라인에 스타일을 적용하는 가상 요소 생성
::selection 해당 요소에서 사용자가 선택한 부분만 선택할 때 사용
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box{width: 100px; height: 100px; background-color: yellowgreen; margin: 0 0 20px; position: relative;}
        .box::before{content:'앞'; display:block; background-color: aqua;
            position: absolute; left:0; top:25%; width: 10px; height: 50%;
        }
        .box::after{content: '뒤'; display: block; background-color: skyblue;
            position: absolute; right:0; top:25%; width: 10px; height: 50%;
        }

        .list::before{content: ''; display:block; width: 50px; height: 10px; background-color: pink; border-bottom: 1px solid red;}
        .list::after{content: ''; display: block; width: 50px; height: 10px;background-color: pink; border-top: 1px solid red;}
        .list p::before{content: '* ';}
        .list p::after{content: ' ====';}

        .member{
            width: 200px; height: 100px;
            margin-top: 20px;
            display: flex; flex-direction: row; 
            align-items: center;
            background-color: aquamarine;}
        .member p{margin: 0 auto; position: relative; border: 1px solid black;}
        .member .name::after{content: ''; display: block; width: 3px; height: 100%;
            background-color: red; position: absolute; right: 0; top:0;}
        .member .name:last-of-type::after{display: none;}
    </style>
</head>
<body>
    <h2>가상요소 - pseudo</h2>

    <div class="box">pseudo</div>

    <div class="list">
        <p>테스트</p>
        <p>테스트</p>
        <p>테스트</p>
        <p>테스트</p>
    </div>

    <div class="member">
        <p class="name">이름</p>
        <p class="name">이름</p>
        <p class="name">이름</p>
        <p class="name">이름</p>
    </div>
</body>
</html>

pseudo element.png